var Alert = require('./alert.js');
var request = require('./request.js');
var Paths = require('./paths.js');
var phoneNumberReg = /^1\d{10}$/;
var verifyCodeReg = /^\d{6}$/;
var alyNVC = '';
var isServer = typeof window === 'undefined';
if(!isServer){
  alyNVC = require('./aliyun.js');
  alyNVC.init({
    renderTo: '#captcha',
    appkey: 'FFFF0N0N0000000038C8',
    scene: 'nvc_bbs',
    isH5: 'false',
    popUp: true,
    nvcCallback: function () { },
  });
}

var getSmsCode = function(obj){
    return new Promise(function(resolve,reject){
        if (!phoneNumberReg.test(obj.mobile)) {
            Alert('请输入正确格式的手机号码');
            return;
          }
          obj.verifyCode = alyNVC.getSubmitVal();
          request.post(Paths.smsSend, obj).then(function (res) {
            if (res.success) {
                resolve(res)
            } else {
              Alert('短信验证码发送失败');
            }
          })
    })
}

var getLogin = function(obj){
    return new Promise(function(resolve,reject){
        if (!phoneNumberReg.test(obj.mobile)) {
            Alert('请输入正确格式的手机号码');
            return;
          }
          if (!verifyCodeReg.test(obj.smsCode)) {
            Alert('请输入正确格式的短信验证码');
            return;
          }
          if (!obj.isReadPrivacy) {
            Alert('请确认并阅读隐私政策');
            return;
          }
          delete obj.isReadPrivacy
          request.post(Paths.loginByPhone,obj).then(function(res){
            if(res.success){
              resolve(res);
            }else {
              Alert(res.msg || '登录失败');
            }
          });
    })
}


var filterParams = function (params,otherNotes){
  var blackNotes = ['isReadPrivacy','res','isPc'].concat(otherNotes);
  var newObj = {};
  for(var key in params){
    if(blackNotes.indexOf(key) === -1){
      newObj[key] = params[key]
    }
  }
  return newObj
}

module.exports = {
    getLogin:getLogin,
    getSmsCode:getSmsCode,
    filterParams:filterParams
}